//
//  QZHomeViewController.m
//  QZRefreshData
//
//  Created by 弘德集团 on 2018/4/12.
//  Copyright © 2018年 弘德集团. All rights reserved.
//

#import "QZHomeViewController.h"
#import "QZRefreshHeaderView.h"
#import "SDRefreshHeaderView.h"
#import "QZRefreshFooterView.h"
#import "UIView+Frame.h"
#define kQZTimeLineRefreshHeaderRotateAnimationKey @"RotateAnimationKey"
typedef enum {
    QZRefreshHeaderViewStyleJD,
    QZRefreshHeaderViewStyleWX,
} QZRefreshHeaderViewStyle;

@interface QZHomeViewController ()<UITableViewDelegate,UITableViewDataSource,QZRefreshViewAnimationDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) QZRefreshHeaderView *headerView;
@property (nonatomic, strong) SDRefreshHeaderView *sdHeaderView;
@property (nonatomic, strong) QZRefreshFooterView *footer;
@property (nonatomic, strong) NSArray *dataSource;

@property (nonatomic, strong) UIImageView *animationView;
@property (nonatomic, strong) UIImageView *boxView;
@property (nonatomic, weak) UILabel *label;

@property (nonatomic, assign) QZRefreshViewStyle refreshStyle;
@property (nonatomic, strong) CABasicAnimation *rotateAnimation;

@end

@implementation QZHomeViewController

- (CABasicAnimation *)rotateAnimation
{
    if (!_rotateAnimation) {
        _rotateAnimation = [[CABasicAnimation alloc] init];
        _rotateAnimation.keyPath = @"transform.rotation.z";
        _rotateAnimation.fromValue = @0;
        _rotateAnimation.toValue = @(M_PI *2);
        _rotateAnimation.duration = 1.0;
        _rotateAnimation.repeatCount = MAXFLOAT;
    }
    return _rotateAnimation;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"Home";
//    self.navigationController.navigationBar.translucent = YES;
    //切换语言
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"HomeVCCell"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00f];
    self.dataSource = @[@"🐹UITableView",@"🐼UITableView_GIF",@"🐽UITableView_DIY",
                        @"🐮UICollectionView",@"🦁UICollectionView_GIF",@"🐸UICollectionView_DIY",
                        @"🐯UIWebView",@"🎹UITextView",@"🐶京东",@"🐱天猫",@"🍆淘宝",@"🐨考拉海购",
                        @"🥕美团外卖",@"🌽网易新闻",@"🍠今日头条",@"🐷飞猪旅行",@"🦋饿了么"];
    UIImageView *bgImg = [UIImageView new];
    bgImg.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 200);
    bgImg.backgroundColor = [UIColor greenColor];
    self.tableView.tableHeaderView = bgImg;
    self.tableView.contentInset = UIEdgeInsetsMake(-64, 0, 0, 0);
    [self setupHeader];
    [self setupFooter];
//    [self sdHeaderRefresh];
}
- (void)sdHeaderRefresh
{
    SDRefreshHeaderView *header = [SDRefreshHeaderView refreshView];
    header.scrollView = self.tableView;
//    [header addToScrollView:self.tableView];
    
    __weak SDRefreshHeaderView *weakHeader = header;
    __weak typeof(self) weakSelf = self;
    header.beginRefreshingOperation = ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [weakSelf.tableView reloadData];
            [weakHeader endRefreshing];
        });
    };
}
- (void)setupHeader
{
    
//    QZRefreshHeaderView *refreshHeader = [QZRefreshHeaderView refreshView];
    
    QZRefreshHeaderView *refreshHeader = [QZRefreshHeaderView refreshViewWithStyle:QZRefreshViewStyleCustom];
//    refreshHeader.frame = CGRectMake(0, 70, self.view.width, 70);
    refreshHeader.backgroundColor = [UIColor clearColor];
    refreshHeader.delegate = self;
    
    //默认是在navigationController环境下，如果不是在此环境下，请设置refreshHeader.isEffectedByNavigationController = NO;
    [refreshHeader addToScrollView:self.tableView];
    
    __weak QZRefreshHeaderView *weakRefreshView = refreshHeader;
    __weak typeof(self)weakSelf = self;
    refreshHeader.beginRefreshingOperation = ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [weakSelf.tableView reloadData];
            [weakRefreshView endRefreshing];
        });
    };
    [self WeiXinAnimationAddView:refreshHeader];
    self.refreshStyle = QZRefreshHeaderViewStyleWX;
    //进入页面自动加载一次数据
    [refreshHeader autoRefreshWhenViewDidAppear];
    
    
}
- (void)setupFooter
{
    QZRefreshFooterView *refreshFooter = [QZRefreshFooterView refreshViewWithStyle:QZRefreshViewStyleClassical];
    [refreshFooter addToScrollView:self.tableView];
    [refreshFooter addTarget:self refreshAction:@selector(footerRefresh)];
    _footer = refreshFooter;
}
- (void)footerRefresh
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        self.totalRowCount += 2;
        [self.tableView reloadData];
        [self.footer endRefreshing];
    });
}
/** 京东的动画 */
- (void)JDAnimationAddView:(QZRefreshHeaderView *)refreshHeader
{
    //动画view
    UIImageView *animationView = [[UIImageView alloc] init];
    animationView.frame = CGRectMake(30, 45, 40, 40);
    animationView.image = [UIImage imageNamed:@"staticDeliveryStaff"];
    [refreshHeader addSubview:animationView];
    _animationView = animationView;
    
    NSArray *images = @[[UIImage imageNamed:@"deliveryStaff0"],
                        [UIImage imageNamed:@"deliveryStaff1"],
                        [UIImage imageNamed:@"deliveryStaff2"],
                        [UIImage imageNamed:@"deliveryStaff3"]
                        ];
    _animationView.animationImages = images;
    
    UIImageView *boxView = [[UIImageView alloc] init];
    boxView.frame = CGRectMake(150, 10, 15, 8);
    boxView.image = [UIImage imageNamed:@"box"];
    [refreshHeader addSubview:boxView];
    _boxView = boxView;
    
    UILabel *label= [[UILabel alloc] init];
    label.text = @"下拉加载最新数据";
    label.frame = CGRectMake((self.view.bounds.size.width - 200) * 0.5, 5, 200, 20);
    label.textColor = [UIColor grayColor];
    label.font = [UIFont systemFontOfSize:14];
    label.textAlignment = NSTextAlignmentCenter;
    [refreshHeader addSubview:label];
    _label = label;
    
}

- (void)WeiXinAnimationAddView:(QZRefreshHeaderView *)headerRefresh
{
    UIImageView *imageView = [UIImageView new];
    imageView.frame = CGRectMake(0, headerRefresh.height *0.5-20, 40, 40);
    imageView.image = [UIImage imageNamed:@"ff_IconShowAlbum"];
    [headerRefresh addSubview:imageView];
    self.animationView = imageView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeVCCell"];
    cell.textLabel.text = self.dataSource[indexPath.row];
    return cell;
}
 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

#pragma mark - QZRefreshView Animation Delegate
- (void)refreshView:(QZRefreshView *)refreshView didBecomeNormalStateWithMovingProgress:(CGFloat)progress
{
    refreshView.hidden = NO;
    if (progress == 0) {
        if (self.refreshStyle == QZRefreshHeaderViewStyleJD) {
            _animationView.transform = CGAffineTransformMakeScale(0.1, 0.1);
            _boxView.hidden = NO;
            _label.text = @"下拉加载数据";
        } else {
            [_animationView.layer removeAnimationForKey:kQZTimeLineRefreshHeaderRotateAnimationKey];
            [UIView animateWithDuration:0.3 animations:^{
                self.animationView.transform = CGAffineTransformIdentity;
            }];
        }
        
        [_animationView stopAnimating];
    }
//    self.animationView.transform = CGAffineTransformConcat(CGAffineTransformMakeTranslation(progress *10, - 20 *progress), CGAffineTransformMakeScale(progress, progress));
//    self.boxView.transform = CGAffineTransformMakeTranslation(- progress *85, progress *35);
}

- (void)refreshView:(QZRefreshView *)refreshView didBecomeRefreshingStateWithMovingProgress:(CGFloat)progress
{
    if (self.refreshStyle == QZRefreshHeaderViewStyleJD) {
        _label.text = @"客官别急，正在加载数据...";
        [UIView animateWithDuration:1.5 animations:^{
            self.animationView.transform = CGAffineTransformMakeTranslation(200, -20);
        }];
    } else {
//        [self.animationView.layer addAnimation:_rotateAnimation forKey:kQZTimeLineRefreshHeaderRotateAnimationKey];
    }
    
}
- (void)refreshView:(QZRefreshView *)refreshView didBecomeWillRefreshStateWithMovingProgress:(CGFloat)progress
{
    if (self.refreshStyle == QZRefreshHeaderViewStyleJD) {
        _boxView.hidden = YES;
        _label.text = @"放开我，我才帮你加载数据";
        _animationView.transform = CGAffineTransformConcat(CGAffineTransformMakeTranslation(10, -20), CGAffineTransformMakeScale(1, 1));
        [_animationView startAnimating];
    } else {
        
        _rotateAnimation = [[CABasicAnimation alloc] init];
        _rotateAnimation.keyPath = @"transform.rotation.z";
        _rotateAnimation.fromValue = @0;
        _rotateAnimation.toValue = @(M_PI *2);
        _rotateAnimation.duration = 1.0;
        _rotateAnimation.repeatCount = MAXFLOAT;
        
        [self.animationView.layer addAnimation:_rotateAnimation forKey:kQZTimeLineRefreshHeaderRotateAnimationKey];
    }
    
}

@end
